package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.StaffCo;
import com.engineering.elink.common.Constant;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.dao.FollowMapper;
import com.engineering.elink.dao.StaffMapper;
import com.engineering.elink.dao.UserMapper;
import com.engineering.elink.domain.Follow;
import com.engineering.elink.domain.Staff;
import com.engineering.elink.service.StaffService;

@Service
public class StaffServiceImpl implements StaffService {

	@Autowired
	private StaffMapper staffMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private FollowMapper followMapper;

	@Override
	public synchronized boolean staff(String userId, String staffUserId) {
		Map<String, Object> user = userMapper.selectByUserId(userId);
		Map<String, Object> staffUser = userMapper.selectByUserId(staffUserId);
		if (!userId.equals(staffUserId) && user != null && staffUser != null
				&& (int) staffUser.get("userType") == Constant.personUserType
				&& (int) user.get("userType") == Constant.companyUserType) {
			// 先判断是否存在关注
			Follow followInSql = followMapper.selectByUserIdAndFollowUserId(
					userId, staffUserId);
			if (followInSql != null) {
				Staff staffInSql = staffMapper.selectByUserIdAndStaffUserId(
						userId, staffUserId);
				if (staffInSql != null) {
					staffMapper.deleteByPrimaryKey(staffInSql.getStaffId());
					return true;
				} else {
					Staff staff = new Staff();
					staff.setCreateTime(new Date());
					staff.setStaffUserId(staffUserId);
					staff.setUserId(userId);
					staffMapper.insertSelective(staff);
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public Map<String, Object> getStaffList(StaffCo staffCo) {
		String userId = staffCo.getUserId();
		Map<String, Object> user = userMapper.selectByUserId(userId);
		if (user != null && ((int)user.get("userType") == Constant.companyUserType)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("list", staffMapper.selectStaffList((staffCo)));
			map.put("Pagination", new Pagination(staffCo, staffMapper.selectStaffListCount(staffCo)));
			return map;
		}
		return null;
	}

}
